package app

import "sync"

type RouterServer struct {
	prefix      string
	middlewares []MiddleWare
	lock        sync.RWMutex
}

type routerNode struct {
	patten      string
	method      string
	middlewares []MiddleWare
	appHandler  func(*Context) error
}

var routers []routerNode

func NewRouter(prefix string, middlewares ...MiddleWare) *RouterServer {

	middlewares = reverseMiddleWare(middlewares)
	return &RouterServer{
		prefix:      prefix,
		middlewares: middlewares,
	}
}

// GroupRouter 子群组路由
func (r *RouterServer) GroupRouter(prefix string, middlewares ...MiddleWare) *RouterServer {
	middlewares = append(middlewares, r.middlewares...)
	return &RouterServer{
		prefix:      prefix,
		middlewares: middlewares,
	}
}

// GET 注册 get 请求
func (r *RouterServer) GET(patten string, handler func(ctx *Context) error) {
	r.appendRoute("GET", patten, handler)
}

// POST 注册 post 请求
func (r *RouterServer) POST(patten string, handler func(ctx *Context) error) {
	r.appendRoute("POST", patten, handler)
}

// PUT 注册 put 请求
func (r *RouterServer) PUT(patten string, handler func(ctx *Context) error) {
	r.appendRoute("PUT", patten, handler)
}

// DELETE 注册 delete 请求
func (r *RouterServer) DELETE(patten string, handler func(ctx *Context) error) {
	r.appendRoute("DELETE", patten, handler)
}

// ALL 兼容所有请求
func (r *RouterServer) ALL(patten string, handler func(ctx *Context) error) {
	r.appendRoute("ALL", patten, handler)
}

// appendRoute 添加路由节点
func (r *RouterServer) appendRoute(method string, patten string, handler func(ctx *Context) error) {
	r.lock.Lock()
	defer r.lock.Unlock()

	routers = append(routers, routerNode{r.prefix + patten, method, r.middlewares, handler})
}
